package com.huitone.gddw.controller.login;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bin.common.utils.DateTimeUtils;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SmLog;  
import com.huitone.gddw.dao.entity.Users;
import com.huitone.gddw.service.impl.system.timer.TimerTaskUsers;   
import com.huitone.gddw.service.system.IRoleService;
import com.huitone.gddw.service.system.IUsersService;
import com.huitone.gddw.utils.CaptchaUtil; 
import com.huitone.gddw.utils.CipherPTUtils;
import com.huitone.gddw.utils.ContextPropertiesUtils;

import cn.com.jit.csp.cypher.cipher.CertAuthClient;
import cn.com.jit.csp.cypher.result.AuthSignResult;
//import cn.com.jit.csp.cypher.utils.KeyUtil;
import cn.com.jit.csp.cypher.utils.KeyUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

//import com.huitone.gddw.smsclient.SendSmsClient;

//import com.huitone.gddw.utils.MD5Util;
@Controller
@RequestMapping(value="login")
public class LoginController extends CommonController {  

	private final static Logger LOGGER = Logger.getLogger(LoginController.class);
	
	@Autowired
	private IUsersService usersService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
    private StringRedisTemplate stringRedisTemplate;
	
	@ResponseBody
	@RequestMapping(value="test",method=RequestMethod.GET)
	public String test(){
		return "hello";
	}
	
	/*@RequestMapping(value="toLogin")
	public String toLogin() {
		return "login";
	}*/
	
	
//	@ResponseBody
//	@RequestMapping(value="/testwpn", method=RequestMethod.POST)
//	public Map<String, Object> test(String username, String password, HttpServletRequest request, HttpSession session) {
//		String parameter = request.getParameter("test");
//		
//		
//		
//		System.out.println("到达测试方法    username="+username +"  password="+password+"  test="+parameter);
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		return map;
//	}
//	@ResponseBody
//	@RequestMapping(value="/testwpn2", method=RequestMethod.POST)
//	public Map<String, Object> test2(@RequestBody JSONObject body,String username, String password, HttpServletRequest request, HttpSession session) {
//		String parameter = request.getParameter("test");
//		System.out.println("JSONObject == "+body.toString());
//		
//		System.out.println("到达测试方法    username="+username +"  password="+password+"  test="+parameter);
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		return map;
//	}
//
//	
//	@ResponseBody
//	@RequestMapping(value="/testwpn21", method=RequestMethod.POST)
//	public JSONObject test21() {
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		map.put("test21", "这是test21接口,没有参数,,,,,,,,只有返回值,JSONObject对象");
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
//	
//	
//	
//	@ResponseBody
//	@RequestMapping(value="/testwpn3", method=RequestMethod.POST)
//	public Map<String, Object> test3(@RequestBody JSONObject body) {
//		if(body != null) {
//			System.out.println("testwpn3  JSONObject.toString()   == "+body.toString());
//			Object username = body.get("username");
//			Object password = body.get("password");
//			Object test = body.get("test");
//			System.out.println("username = "+username);
//			System.out.println("password = "+password);
//			System.out.println("test = "+test);
//		}
//		
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		return map;
//	}
//	@ResponseBody
//	@RequestMapping(value="/testwpn31", method=RequestMethod.POST)
//	public JSONObject test31(@RequestBody JSONObject body) {
//		if(body != null) {
//			System.out.println("test31  JSONObject.toString()   == "+body.toString());
//			Object username = body.get("username");
//			Object password = body.get("password");
//			Object test = body.get("test");
//			System.out.println("username = "+username);
//			System.out.println("password = "+password);
//			System.out.println("test = "+test);
//		}
//		
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
//	@ResponseBody
//	@RequestMapping(value="/testwpn4", method=RequestMethod.POST)
//	public Map<String, Object> test4(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("test4 JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password"));
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		return map;
//	}
//	@ResponseBody
//	@RequestMapping(value="/testwpn5", method=RequestMethod.POST)
//	public JSONObject test5(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("testwpn5  JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password"));
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
////		JSONObject jsonObject = JSONObject.parseObject(map.toString());
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
//	
//	@ResponseBody
//	@RequestMapping(value="/testwpn6", method=RequestMethod.POST)
//	public String test6(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("testwpn6接受 JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password"));
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
////		String json = JSONObject.toJSONString(map);
//		return map.toString();
//	}

	
//	//json格式返回user对象,,怎么返回,,,,,,
//	@ResponseBody
//	@RequestMapping(value="/testwpn9", method=RequestMethod.POST)
//	public JSONObject test9(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("test4 JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password")); 
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		
//		SvrNodeDef wo = new SvrNodeDef();
//		wo.equals("时段时段所多");
//		wo.setSvrNodeName("的地方疯疯癫癫");
//		
//		map.put("date",wo );
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
//	
//	@ResponseBody
//	@RequestMapping(value="/testwpn91", method=RequestMethod.POST)
//	public JSONObject test91(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("test4 JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password")); 
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
//		
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
//	@ResponseBody
//	@RequestMapping(value="/testwpn92", method=RequestMethod.POST)
//	public JSONObject test92(@RequestBody Map<String, String> map1) {
//		
//		System.out.println("test4 JSONObject == "+map1.toString());
//		System.out.println("username == "+map1.get("username"));
//		System.out.println("password == "+map1.get("password")); 
//		System.out.println("test == "+map1.get("test"));
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("AAA", "88888888");
//		map.put("XXX", "OOOOOOO");
////		Wo wo = new Wo();
////		wo.name="顺丰速递";
////		
////		map.put("date",wo );
//		JSONObject json = new JSONObject(map);
//		return json;
//	}
	
	
	//登陆之前获取秘钥
	@ResponseBody
	@RequestMapping(value="/getPrivateKey")
	public String getPrivateKey() {
		//获取publicKey
    	Map<Object, Object> MMPTpublicKey = stringRedisTemplate.opsForHash().entries("MMPTpublicKey");
    	if(MMPTpublicKey.size() <= 0) {
    		return "";
    	}
    	Iterator<Entry<Object, Object>> iterator = MMPTpublicKey.entrySet().iterator();
    	Entry<Object, Object> entry = iterator.next();
    	String publicKey = entry.getKey().toString();
    	LOGGER.info("test 274行      前端获取秘钥成功    publicKey==     "+publicKey); 
		return publicKey;
	}
	
	/**
	 * 系统登录
	 * @param username 用户名
	 * @param password 密码
	 * @param request
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public Map<String, Object> login(String username, String password, HttpServletRequest request, HttpSession session) {
//		try {
//			String sm2PrivateKeyBase64 = ContextPropertiesUtils.getProperty("sm2PrivateKeyBase64").toString();
////			PrivateKey sm2PrivateKey= KeyUtil.SM2KeyBase64ConvertPirvateKey("MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgt4Tmuz+2RYC1fkrnOenTszOxCp0Wh5BmppeTzDaGCfCgCgYIKoEcz1UBgi2hRANCAAQFm7MgGLqcJ2PT7KXvdOTbaVyNh9ylIU403OJYdEHldseL9kuDk0gph+V9KnZWC3LfCAGz0JY7QqLY8neWH7Hs");//私钥的base64值 
//			LOGGER.info("test   290行     /login  获取sm2PrivateKey对象     之前      ");
//			System.out.println("test   290行     /login  获取sm2PrivateKey对象     之前      ");
//			PrivateKey sm2PrivateKey= KeyUtil.SM2KeyBase64ConvertPirvateKey(sm2PrivateKeyBase64);//私钥的base64值
//			LOGGER.info("test   290行     /login  获取sm2PrivateKey对象     之后      ");
//			System.out.println("test   290行     /login  获取sm2PrivateKey对象     之后      ");
//			AuthSignResult sm2AuthSignResult2= (AuthSignResult) CertAuthClient.keyAuthCodeSign(sm2PrivateKey,"NTM3MjZhYjIwZGM1NDRiOTg2NDRiNDYzZjY4MTQyOWY=");//   autCode
//			LOGGER.info("test   293行      /login  获取sm2AuthSignResult2对象 "+sm2AuthSignResult2);
//			String signature = sm2AuthSignResult2.getSignature();
//			String signAlgorithm = sm2AuthSignResult2.getSignAlgorithm();
////			System.out.println("签名值    "+signature);
////			System.out.println("签名算法    "+signAlgorithm);
//			LOGGER.info("授权码签名成功:   签名值:    "+signature+"    签名算法: "+signAlgorithm);
//			LOGGER.info("test  298行   /login   授权码签名成功:   签名值"+ signature+"    签名算法: "+signAlgorithm);
//		} catch (Exception e) {
//			LOGGER.info("test  300   /login   Exception   异常捕获 ");
//		}
		
		
		
		
		String userId = username;
		super.logType = SmLog.LOGTYPE_LOGIN;
		super.logContent = "[" + userId + "]系统登陆";
		Map<String, Object> map = new HashMap<String, Object>();
		// 对用户名和密码进行判空处理
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(password)) {
			map.put("isSuccess", false);
			map.put("code", "1");
			map.put("msg", "登录失败，用户名和密码不能为空！");
			super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
			return map;
        }
		
		//图片验证码
		if (session.getAttribute("captchaDate") != null) {
			Date captchaDate = (Date)session.getAttribute("captchaDate");
			if (captchaDate.before(new Date())) {
				map.put("isSuccess", false);
				map.put("code", "2");
				map.put("msg", "验证码已失效，请重新输入！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
			//图片验证码
			String captcha = request.getParameter("captcha");
			if(!captcha.toUpperCase().equals(session.getAttribute("captcha").toString())){
				map.put("isSuccess", false);
				map.put("code", "3");
				map.put("msg", "验证码不正确！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
		}
		
		/*
		 * 密码平台  解密,,前端使用密码平台加密
		 */
		String isEncrypt = request.getParameter("isEncrypt");//0是     1不是 
		LOGGER.info("用户:"+username+" 是否使用国密插件登录     isEncrypt是  "+isEncrypt );
	    if("0".equals(isEncrypt)) {
	    	//获取tonken
	    	Map<Object, Object> mapTonken = stringRedisTemplate.opsForHash().entries("token");
	    	if(mapTonken.size() <=0) {
	    		// 重新认证身份
//	    		CipherPTUtils.authenticationCipher();
	    		LOGGER.error("用户:"+username+" , 登录失败，获取token" );
	    		map.put("isSuccess", false);
				map.put("code", "98");
				map.put("msg", "登录失败，获取token！");
	    		return map;
	    	}
	    	Iterator<Entry<Object, Object>> iterator = mapTonken.entrySet().iterator();
	    	Entry<Object, Object> entry = iterator.next();
	    	String token = entry.getKey().toString();
	    	String expirationTime = entry.getValue().toString();
	    	//tonken是否过期
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	try {
				Date expirationDate = sdf.parse(expirationTime);
				long currentTimeMillis = System.currentTimeMillis();
				Date currentDate = new Date(currentTimeMillis);
				boolean before = expirationDate.before(currentDate);
				if(before == true) {//过期时间在当前时间前面, 表示过期了       true过期       fasle不过期
					//tonken时间过期 重新认证身份
					LOGGER.error("登陆接口     tonken时间过期    重新认证身份  " );
					Map resultMap = CipherPTUtils.authenticationCipher(); 
					if(resultMap != null) {
						Iterator<Entry<Object, Object>> entr = resultMap.entrySet().iterator();
						Entry<Object, Object> entry2 = entr.next();
						token=entry2.getKey().toString();
					}
				}
			}catch (ParseException e) {
				LOGGER.error("时间解析出异常：" + e.getMessage(), e);
			}
	    	
	    	//获取 密钥标识keyCode
	    	Map<Object, Object> MMPTkeyCode = stringRedisTemplate.opsForHash().entries("MMPTkeyCode");
	    	if(MMPTkeyCode.size() <= 0) {
	    		//创建密钥标识keyCode
	    		CipherPTUtils.getKeyPair();
	    		MMPTkeyCode = stringRedisTemplate.opsForHash().entries("MMPTkeyCode");
	    	}
	    	Iterator<Entry<Object, Object>> iteratorMMPTkeyCode = MMPTkeyCode.entrySet().iterator();
	    	Entry<Object, Object> entrykeyCode = iteratorMMPTkeyCode.next();
	    	String keyCode = entrykeyCode.getKey().toString();
	    	
	    	//解密登陆密码
	    	String decryptPassword = CipherPTUtils.decryptText(password, token,keyCode);
	    	if(decryptPassword != null) {
	    		LOGGER.info("解密之前 password    "+password );
	    		final BASE64Decoder decoder = new BASE64Decoder();
	    		//解码
    			try {
    				password=new String(decoder.decodeBuffer(decryptPassword), "UTF-8");
//					System.out.println(new String(decoder.decodeBuffer(decryptPassword), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					LOGGER.info("BASE64  解码password出异常   "+e.getMessage());
				} catch (IOException e) {
					LOGGER.info("BASE64  解码password出异常    "+e.getMessage());
				}
	    		LOGGER.info("解密之后 password    "+password );
	    	}else {
	    		LOGGER.error("用户密码解码失败 password  "+password );
	    		map.put("isSuccess", false);
				map.put("code", "102");
				map.put("msg", "登陆异常，请联系管理员！");
				return map;
	    	}
	    	
	    	//解密用户名
	    	String userIddecrypt = CipherPTUtils.decryptText(userId, token,keyCode);
	    	if(userIddecrypt != null) {
	    		LOGGER.info("解密之前 userId    "+userId );
	    		final BASE64Decoder decoder = new BASE64Decoder();
	    		//解码
    			try {
    				userId=new String(decoder.decodeBuffer(userIddecrypt), "UTF-8");
    				username= userId;
				} catch (UnsupportedEncodingException e) {
					LOGGER.info("BASE64  解码用户名 出异常   "+e.getMessage());
				} catch (IOException e) {
					LOGGER.info("BASE64  解码用户名 出异常    "+e.getMessage());
				}
	    		LOGGER.info("解密之后 userId    "+userId );
	    	}else {
	    		LOGGER.error("用户名解密失败 userId  "+userId );
	    		map.put("isSuccess", false);
				map.put("code", "101");
				map.put("msg", "登陆异常，请联系管理员！");
				return map;
	    		
	    	}
	    	
	    }
	    
		
		//短信验证码
		/*String captcha = request.getParameter("captcha");
		String key = userId+phone;			
		if (StringUtils.isNotBlank(captcha)) {
			String code = stringRedisTemplate.opsForValue().get(key); //获取短信验证码
			if (code == null) {
				map.put("isSuccess", false);
				map.put("code", "2");
				map.put("msg", "短信验证码已失效，请重新输入！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}else if (!(captcha.equals(code))) {
				map.put("isSuccess", false);
				map.put("code", "3");
				map.put("msg", "短信验证码不正确！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
		}*/
		
//		if (SessionListener.sessionContext.getSessionMap().get(userId) != null){
//			map.put("isSuccess", false);
//			map.put("code", "4");
//			map.put("msg", "禁止同一账号多次登录！");
//			super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
//			return map;
//		}
		
		
		
		
		
		
		try {
			Users user = usersService.getById(userId);
			if (null == user) {
				map.put("isSuccess", false);
				map.put("code", "5");
				map.put("msg", "登录失败，用户名或密码不正确！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}

			if (user.getFailCount() >= Integer.parseInt(ContextPropertiesUtils.getProperty("login_fail_times"))) {
				Long unlockTime = Long.parseLong(ContextPropertiesUtils.getProperty("user_unlock_time")) * 60 * 1000;
				Date date = new Date(user.getFreezeDate().getTime() + unlockTime);
				if (new Date().before(date)) {
					map.put("isSuccess", false);
					map.put("code", "6");
					map.put("msg", "该用户已被冻结，将于 " + DateTimeUtils.dateToStr(date) + " 解锁！");
					super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
					return map;
				}else {
					unlockUser(user);
				}
//				unlockUser(user);
			}
			
			
		
			
//			password = MD5Util.encode(password);
			if (!password.equals(user.getPwd())) {
				LOGGER.info("test  522行          password==  "+password  +"        user.getPwd()" +user.getPwd());
				LOGGER.info("test  523行          user.toString()==  "+user.toString());
				
				map.put("isSuccess", false);
				map.put("code", "7");
				map.put("msg", "登录失败，用户名或密码不正确！");
				
				int failCount = usersService.addFailCount(user);
				if (failCount >= Integer.parseInt(ContextPropertiesUtils.getProperty("login_fail_times"))) {
					usersService.freezeUser(user);
					this.autoUnlockUser(user);
					map.put("code", "8");
					map.put("msg", "密码错误，该用户已被冻结，" + ContextPropertiesUtils.getProperty("user_unlock_time") + "分钟后解锁！");
					
				}
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
			if (StringUtils.isBlank(user.getStatus()) || user.getStatus().equals("0")) {
				map.put("isSuccess", false);
				map.put("code", "9");
				map.put("msg", "该用户无效");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
			if (user.getPwdValidDate() != null && user.getPwdValidDate().before(new Date())) {
				map.put("isSuccess", false);
				map.put("code", "10");
				map.put("msg", "该用户密码已过期，请联系管理员！");
				super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
				return map;
			}
			
			if (user.getFailCount() > 0) {
				unlockUser(user);
			}
			
			user.setOnlineStatus(Users.ONLINE_STATUS_ON);
			usersService.update(user);
			
			// 将用户信息保存到 session 中
			session.setAttribute("curLoginUser", user);
			session.setAttribute("isAdmin", roleService.isAdmin(user.getUserId()));
			session.setAttribute("userId", user.getUserId());
			
			stringRedisTemplate.opsForValue().set(user.getUserId(), session.getId());
			
			Map<String, Object> mapUser = new HashMap<String, Object>();
			mapUser.put("userId", user.getUserId());
			mapUser.put("userName", user.getUserName());
			
			map.put("isSuccess", true);
			map.put("code", "0");
			map.put("msg", "登录成功！");
			map.put("user", mapUser);
			super.saveSmLog(super.logType, super.logContent, super.logResult);
			return map;
		} catch (Exception e) {
			LOGGER.error("登录出现异常：" + e.getMessage(), e);
			map.put("isSuccess", false);
			map.put("code", "-1");
			map.put("msg", "登录异常！");
			super.saveSmLog(super.logType, super.logContent, SmLog.RESULT_FAIL);
			return map;
		}
		
	}
	
	/**
	 * 退出系统
	 * @param request
	 * @param session
	 */
	@ResponseBody
	@RequestMapping(value="/logout")
	public Map<String, Object> logout(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			String userId = (String)session.getAttribute("userId");
			Users user = usersService.getById(userId);
			user.setOnlineStatus(Users.ONLINE_STATUS_OFF);
			usersService.update(user);
			
			session.invalidate();
			
			map.put("isSuccess", true);
			map.put("msg", "退出成功！");
			return map;
		} catch (Exception e) {
			LOGGER.error("退出系统出现异常：" + e.getMessage(), e);
			map.put("isSuccess", false);
			map.put("msg", "退出异常！");
			return map;
		}
	}
	
	/**
	 * 修改密码
	 * @param userId 工号
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping(value="/changePwd")
	public Map<String, Object> changePwd(String userId, String oldPassword, String newPassword, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		String uid = (String)session.getAttribute("userId");
		if (!userId.equals(uid)) {
			map.put("isSuccess", false);
			map.put("msg", "修改失败！");
			return map;
		}
		
		if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) {
			map.put("isSuccess", false);
			map.put("msg", "密码不能为空！");
			return map;
		}
		if (newPassword.equals(oldPassword)) {
			map.put("isSuccess", false);
			map.put("msg", "新密码与旧密码一致！");
			return map;
		}
		try {
			Users user = usersService.getById(userId);
//			oldPassword = MD5Util.encode(oldPassword);
			if (!oldPassword.equals(user.getPwd())) {
				map.put("isSuccess", false);
				map.put("msg", "旧密码不正确，无法修改！");
				return map;
			}
//			newPassword = MD5Util.encode(newPassword);
			user.setPwd(newPassword);
			initPwdVaildDate(user);
			usersService.update(user);
			map.put("isSuccess", true);
			map.put("msg", "修改成功！");
			return map;
		} catch (Exception e) {
			LOGGER.error("修改密码出现异常：" + e.getMessage(), e);
			map.put("isSuccess", false);
			map.put("msg", "修改异常！");
			return map;
		}
		
	}
	
	/**
	 * 获取密码有效期
	 * @param entity Users
	 * @return Users
	 */
	private Users initPwdVaildDate(Users entity) {
		long day = Long.valueOf(ContextPropertiesUtils.getProperty("cryptoperiod"));
		entity.setPwdValidDate(new Date(new Date().getTime() + day * 24 * 60 * 60 * 1000));
		return entity;
	}
	
	/**
	 * 验证是否初始密码
	 * @param userId 工号
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping(value="/validPwd")
	public Map<String, Object> validPwd(String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Users user = usersService.getById(userId);
			if (user.getPwdValidDate() != null) {
				long pwdVaildDate = user.getPwdValidDate().getTime();
				long day = Long.valueOf(ContextPropertiesUtils.getProperty("ahead_day"));
				long difTime = pwdVaildDate - new Date().getTime();
				if (difTime <= day * 24 * 60 * 60 * 1000) {
					map.put("isSuccess", false);
					map.put("code", 2);
					map.put("msg", "该密码将于 "+DateTimeUtils.dateToStr(user.getPwdValidDate())+" 过期，请及时修改密码！");
					return map;
				}
			}
//			if (user.getPwd().equals(MD5Util.encode(ContextPropertiesUtils.getProperty("init_pwd")))) {
			if (user.getPwd().equals(ContextPropertiesUtils.getProperty("init_pwd"))) {
				map.put("isSuccess", false);
				map.put("code", 1);
				map.put("msg", "为保证安全性，请及时修改初始密码！");
				return map;
			}
			map.put("isSuccess", true);
			map.put("msg", "验证成功！");
			map.put("code", 0);
			return map;
		} catch (Exception e) {
			LOGGER.error("验证密码出现异常：" + e.getMessage(), e);
			map.put("isSuccess", false);
			map.put("msg", "验证异常！");
			map.put("code", -1);
			return map;
		}
	}
	
	/**
	 * 获取验证码
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/captcha", method = RequestMethod.GET)
    @ResponseBody
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CaptchaUtil.outputCaptcha(request, response);
    }
	
	/**
	 * 定时解锁用户
	 * @param entity 用户
	 */
	private void autoUnlockUser(Users entity) {
		// 获取解锁毫秒数
		Long unlockTime = Long.parseLong(ContextPropertiesUtils.getProperty("user_unlock_time")) * 60 * 1000;
		Date autoUnlockDate = new Date(entity.getFreezeDate().getTime() + unlockTime);
		
		Timer timer = new Timer();
		timer.schedule(new TimerTaskUsers(usersService, entity), autoUnlockDate);
	}
	
	/**
	 * 解锁用户
	 * @param entity 用户
	 */
	private void unlockUser(Users entity) {
		entity.setFailCount(0);
		entity.setLockStatus(Users.LOCK_STATUS_NORMAL);
		entity.setFreezeDate(null);
		usersService.update(entity);
	}
	
	/*@RequestMapping(value = "/sendSms", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject sendSms(@RequestBody() JSONObject jsonObj) throws IOException {
		String userName = jsonObj.getString("userName");
		String phone = jsonObj.getString("phone");
		JSONObject object = new JSONObject();
		String captcha = String.valueOf(new Random().nextInt(899999) + 100000);
		SmTemplate smTemp = smTemplateService.selectByTemplateType("3");
		String content = smTemp.getSmsContent();
		Map<String, Object> map = new HashMap<>(2);
        map.put("captcha", captcha);
        map.put("time", "3");
		String smsContent = ReplaceUtil.replaceSMS(content, map);
		boolean sendFlag = SendSmsClient.send(phone,smsContent);				
	    if (sendFlag){
		    stringRedisTemplate.opsForValue().set(userName+phone, captcha, 3,TimeUnit.MINUTES); 
		    object.put("code", 0);
			object.put("msg", "success");	    
		}else {
			object.put("code", 5000);
		    object.put("msg", "failed");
		}

		object.put("data", ""); 			
		return object;
	}*/
	
	//测试接口
	/*@RequestMapping(value = "/send", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject sendSmsTest(HttpServletRequest request) throws IOException {
		String smsContent = request.getParameter("content");
		String targetNum = request.getParameter("targetNum");
		JSONObject object = new JSONObject();
		boolean sendFlag = SendSmsClient.send(targetNum,smsContent);	
		//增加oracle和redis流程
		SmTemplate smTemp = smTemplateService.selectByTemplateType("3"); 
		String value = stringRedisTemplate.opsForValue().get("3");
		System.out.println("增加oracle流程和redis流程:"+smTemp+" "+value);
	    if (sendFlag){ 
		    object.put("code", 0);
			object.put("msg", "success");	    
		}else { 
			object.put("code", 5000);
		    object.put("msg", "failed");
		}
	    object.put("reqTransNo", request.getParameter("reqTransNo"));
		object.put("data", ""); 			
		return object;
	}*/
	
}
